package user.listener;



import blog.common.utils.JsonUtil;
import blog.common.utils.MailUtil;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import user.common.dataobject.UserInfo;

import java.io.IOException;


@Configuration
@Slf4j
public class UserRegisterListener {
    @Autowired
    private MailUtil mailUtil;
    //不用再写Configuration类表示队列，交换机，绑定关系
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = "user.exchange",type = "fanout"),
            value = @Queue(value = "user.queue",durable = "true")
    ))
    public void userRegister(Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            String body = new String(message.getBody());
            log.info("用户注册,userInfo:{}",body);
            //发送邮件
            UserInfo  userInfo = JsonUtil.parse(body, UserInfo.class);
            mailUtil.send(userInfo.getEmail(),"恭喜注册成功！",successTest(userInfo));
            channel.basicAck(deliveryTag,true);
        }catch (Exception e) {
            log.error("发送邮件失败! e:{}",e.getMessage());
            channel.basicNack(deliveryTag,true,true);
        }
    }

    private String successTest(UserInfo userInfo) {
         String content = new StringBuilder()
                .append("尊敬的").append(userInfo.getUserName()).append(", 您好! <br/>")
                .append("感谢您注册成为我们博客社区的⼀员! 我们很⾼兴您决定加⼊我们的⼤家庭. <br/>")
                        .append("您的注册信息如下: </br/>")
                        .append("⽤户名:").append(userInfo.getUserName()).append("<br/>")
                        .append("为了确保您的账⼾安全，请妥善保管您的登录信息. 如果使⽤过程中, 遇到任何 问题, 欢迎联系我们的⽀持团队. 553050493@qq.com <br/>")
                .append("再次感谢您的加⼊，我们期待看到您的精彩内容！<br/>")
                .append("最好的祝愿<br/>")
                .append("木火因博客团队").toString();
                        return content;
    }


    /*@RabbitListener(queues = "user.queue")
    public void userRegister(Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            String body = new String(message.getBody());
            log.info("用户注册,userInfo:{}",body);

            channel.basicAck(deliveryTag,true);
        }catch (Exception e) {
            log.error("发送邮件失败! e:{}",e.getMessage());
            channel.basicNack(deliveryTag,true,true);
        }
    }*/
}
